#pragma once

#include "bencode.hpp"

namespace alpha { namespace rpc {

template <typename Stream, template <typename> class Tmpl>
Stream & operator <<(Stream &stream, basic_bencode<Tmpl> const &r)
{
	typedef typename basic_bencode<Tmpl>::integer integer;
	typedef typename basic_bencode<Tmpl>::string string;
	typedef typename basic_bencode<Tmpl>::list list;
	typedef typename basic_bencode<Tmpl>::dictionary dictionary;

	if (integer const *v = r.template pointer<integer>())
		stream << 'i' << *v << 'e';
	else if (string const *v = r.template pointer<string>())
		stream << v->size() << ':' << *v;
	else if (list const *v = r.template pointer<list>())
	{
		stream << 'l';
		for (typename list::const_iterator i = v->begin(); i != v->end(); ++i)
			stream << *i;
		stream << 'e';
	}
	else if (dictionary const *v = r.template pointer<dictionary>())
	{
		stream << 'd';
		for (typename dictionary::const_iterator i = v->begin(); i != v->end(); ++i)
			stream << i->first.size() << ':' << i->first << i->second;
		stream << 'e';
	}
	else
		stream.setstate(std::ios::failbit);
	return stream;
}

}} // namespace alpha::rpc
